﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OA.UI
{
    public static class Comet
    {
        public class CometModel
        {
            public string Key{get;set;}

            public System.Web.Mvc.Async.AsyncManager Async { get; set; }
        }

        static Comet()
        {
            Comets = new List<CometModel>();
        }

        public static List<CometModel> Comets { get; set; }

        /// <summary>
        /// 等待消息 
        /// </summary>
        /// <param name="Key">键，可以重复</param>
        /// <param name="Async">异步控制类，通过这个可以启用等待中的连接</param>
        public static void WaitMsg(string Key, System.Web.Mvc.Async.AsyncManager Async)
        {
            Async.OutstandingOperations.Increment();
            lock (Comets)
            {
                Comets.Add(new CometModel()
                {
                    Key = Key,
                    Async = Async
                });
            }
        }
        /// <summary>
        /// 通知消息，释放等待中的连接
        /// </summary>
        /// <param name="Key">键</param>
        /// <param name="Data">数据</param>
        public static void NotifyMsg(string Key, object Data)
        {
            lock (Comets)
            {
                for (int i = 0; i < Comets.Count; i++)
                {
                    var comet=Comets[i];
                    if (comet.Key == Key)
                    {
                        comet.Async.Parameters.Add("Data", Data);
                        comet.Async.OutstandingOperations.Decrement();
                        Comets.RemoveAt(i--);
                    }
                }
            }
        }
    }
}
